<script setup lang="ts">
import { ref, watch } from "vue";
import Taro, { useRouter, useShareAppMessage } from "@tarojs/taro";

import Page from "@/components/common/Page.vue";
import ByButton from "@/components/ui/ByButton.vue";
import PageHeader from "@/components/common/PageHeader.vue";

import ApiApp from "@/api/app";
import ApiActivity from "@/api/activity";
import useFetch from "@/hooks/useFetch";
import setting from "@/utils/setting";

const { params } = useRouter<{
  batchNum: string;
  actId: string;
}>();

// 小程序码图片地址
const picPath = ref();

// 获取活动详情
const { data } = useFetch<{ detail: any }>(ApiActivity.activityDetailConsumer, {
  defaultParams: { id: +params.actId },
});

// 获取截图图片
const generagePic = (): Promise<string> => {
  return new Promise((resolve, reject) => {
    Taro.createSelectorQuery()
      .select("#couponShare")
      .node()
      .exec((res) => {
        const node = res[0].node;
        node.takeSnapshot({
          type: "file",
          format: "png",
          success: (res) => {
            resolve(res.tempFilePath);
          },
          fail(err) {
            console.log("errr", err);
            reject(err);
          },
        });
      });
  });
};

// 保存至相册
// const saveToAlbum = async () => {
//   // const filePath = await generagePic();

//   Taro.saveImageToPhotosAlbum({
//     filePath: picPath.value,
//     success() {
//       Taro.showToast({ title: "保存成功" });
//     },
//     async fail(err: any) {
//       // 授权拒绝
//       if (err.errno == 103) {
//         const { confirm } = await Taro.showModal({
//           title: "保存失败",
//           content: "需要授权“添加到相册”",
//           confirmText: "去设置",
//         });

//         if (confirm) {
//           Taro.openSetting({});
//         }
//       } else {
//         Taro.showToast({ icon: "none", title: "保存失败" });
//       }
//     },
//   });
// };

// 获取小程序码
const { data: codeURL } = useFetch(ApiApp.customQRCode, {
  // immediate: false,
  showLoading: true,
  defaultParams: {
    path: "packageCoupon/pages/accept",
    page: "packageCoupon/pages/accept",
    scene: params.batchNum,
    env_version: setting.envVersion,
    check_path: false,
    // 透明底
    is_hyaline: true,
  },
  afterFetch: (res: any) => `data:image/jpeg;base64,${res.url}`,
});

watch([data, codeURL], ([d1, d2]) => {
  if (d1 && d2) {
    generagePic().then((res) => {
      picPath.value = res;
    });
  }
});

useShareAppMessage(() => {
  console.log("batchNum", params.batchNum);

  const { title_small_img } = data.value?.detail || {};

  return {
    title: "赠送您嘉年华票券，请查收～",
    path: `/packageCoupon/pages/accept?scene=${params.batchNum}`,
    imageUrl: title_small_img || "/static/images/app-share.jpg",
  };
});
</script>

<template>
  <Page hidden-header-bg body-center class="h-screen bg-black">
    <template #header>
      <PageHeader />
    </template>

    <template #footer>
      <view class="p-3 text-center">
        <view>
          <view class="mb-2 text-sm text-[#BB8654]">长按图片保存/分享</view>
          <!-- <ByButton class="w-2/3" @tap="saveToAlbum">保存到相册</ByButton> -->
          <ByButton class="w-2/3" open-type="share">立即分享</ByButton>
        </view>
        <view class="safe-footer" />
      </view>
    </template>

    <image
      :src="picPath"
      mode="widthFix"
      class="w-[560px]"
      :show-menu-by-longpress="true"
    />
  </Page>

  <view class="fixed -top-full -left-full">
    <snapshot mode="view" id="couponShare">
      <view class="w-[560px] mx-auto bg-primary p-3 rounded-lg">
        <image
          :src="data?.detail?.poster_img || data?.detail?.title_img"
          class="w-full"
          mode="widthFix"
        />

        <view class="flex items-end py-3 text-white">
          <view class="flex-auto mr-1">
            <view class="text-[46px] break-all">
              {{ data?.detail.title }}
            </view>

            <view class="mt-3 text-xs">赠送您嘉年华票券，扫码查收~</view>
          </view>

          <image :src="codeURL" class="w-[160px] h-[160px] flex-none" />
        </view>
      </view>
    </snapshot>
  </view>
</template>
